package cn.jekun.web.agent.action;

import java.sql.Types;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import cn.jekun.component.base.bean.ErrorMsg;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.EncryptUtil;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.core.bean.gen.ErpShop;
import cn.jekun.component.core.bean.gen.RsAgent;
import cn.jekun.component.core.bean.gen.RsUser;
import cn.jekun.component.core.bean.gen.TsAccount;
import cn.jekun.component.core.service.AccountPayService;
import cn.jekun.component.core.service.gen.RsAgentService;
import cn.jekun.component.core.service.gen.RsUserService;
import cn.jekun.component.core.service.gen.TsAccountService;
import cn.jekun.web.agent.service.UserAgentService;
import cn.jekun.web.agent.service.WebAgentService;
/**
 * 安全设置
 * @author twj
 *
 */
@SuppressWarnings("serial")
public class SafeSetAction extends AgentBaseAction{
	private String agentName;
	private String oldMobile;
	private String newMobile;
	private String oldLoginPwd;// 旧登录密码
	private String newLoginPwd;// 新登录密码
	private String oldPayPwd;// 旧支付密码
	private String newPayPwd;// 新支付密码
	@Resource(name = RsAgentService.BEAN_NAME)
	RsAgentService agentService;
	@Resource(name = RsUserService.BEAN_NAME)
	RsUserService userService;
	@Resource(name = TsAccountService.BEAN_NAME)
	TsAccountService accountService;
	@Resource(name = WebAgentService.BEAN_NAME)
	WebAgentService webAgentService;
	@Resource(name = UserAgentService.BEAN_NAME)
	UserAgentService userAgentService;
	@Resource(name = AccountPayService.BEAN_NAME)
	AccountPayService accountPayService;
	public String getAgentName() {
		return agentName;
	}
	public void setAgentName(String agentName) {
		this.agentName = agentName;
	}
	public String getOldMobile() {
		return oldMobile;
	}
	public void setOldMobile(String oldMobile) {
		this.oldMobile = oldMobile;
	}
	public String getNewMobile() {
		return newMobile;
	}
	public void setNewMobile(String newMobile) {
		this.newMobile = newMobile;
	}
	public String getOldLoginPwd() {
		return oldLoginPwd;
	}
	public void setOldLoginPwd(String oldLoginPwd) {
		this.oldLoginPwd = oldLoginPwd;
	}
	public String getNewLoginPwd() {
		return newLoginPwd;
	}
	public void setNewLoginPwd(String newLoginPwd) {
		this.newLoginPwd = newLoginPwd;
	}
	public String getOldPayPwd() {
		return oldPayPwd;
	}
	public void setOldPayPwd(String oldPayPwd) {
		this.oldPayPwd = oldPayPwd;
	}
	public String getNewPayPwd() {
		return newPayPwd;
	}
	public void setNewPayPwd(String newPayPwd) {
		this.newPayPwd = newPayPwd;
	}
	private TsAccount tsAccount;
	

	public TsAccount getTsAccount() {
		return tsAccount;
	}

	public void setTsAccount(TsAccount tsAccount) {
		this.tsAccount = tsAccount;
	}
	/**
	 * 查询代理商账号和绑定手机号码
	 * 
	 * @return
	 */
	public String queryMessage(){
		
		JSONObject jsonObject = new JSONObject();
		//检测是否拥有 权限
		boolean CHANGELOGINPWD = this.coreAuthService.checkRigth(this.getSessionUser().getUserId(), "AGENT_MY_SECURITY_MANAGER");
		boolean CHANGEMOBILE = this.coreAuthService.checkRigth(this.getSessionUser().getUserId(), "AGENT_MY_SECURITY_MANAGER");
		boolean CHANGEPAYPWD = this.coreAuthService.checkRigth(this.getSessionUser().getUserId(), "AGENT_MY_SECURITY_MANAGER");
		boolean CHANGEPERSONMOBILE = this.coreAuthService.checkRigth(this.getSessionUser().getUserId(), "AGENT_MY_SECURITY_MANAGER");
		
		//是否出现按钮
		jsonObject.put("CHANGELOGINPWD",CHANGELOGINPWD) ;
		jsonObject.put("CHANGEMOBILE",CHANGEMOBILE) ;
		jsonObject.put("CHANGEPAYPWD",CHANGEPAYPWD) ;
		jsonObject.put("CHANGEPERSONMOBILE",CHANGEPERSONMOBILE) ;
		
		
        
		agentName = this.getSessionUser().getAgentName();
		oldMobile = this.getSessionUser().getAgentMobile();
		jsonObject.element("agentName", agentName);
		jsonObject.element("oldMobile",oldMobile);
//		return "/agent/safe.jsp";
		jsonObject.element(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
		jsonObject.element(ErrorMsg.KEY_MESSAGE, "调用成功");
		return this.writeJson(jsonObject);
	}
	/**
	 * 显示旧手机号
	 * 
	 * @return
	 */
	public String showMobile() {
		oldMobile = this.getSessionUser().getAgentMobile();
		return "/agent/resetPhone.jsp";
	}

	/**
	 * 重置手机号
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String resetMobile() {
		JSONObject jsonObject = new JSONObject();
		String tempAgentId = this.getSessionUser().getAgentId();
		// 检查是否存在代理商用户
//		formMap.put(RsAgent.COL_AGENT_ID, this.getSessionUser().getAgentId());
//		SqlUtis.prepareSql(formMap, SqlUtis.getSQLRequired(formMap, "a."
//				+ RsAgent.COL_AGENT_ID, Types.VARCHAR, SqlUtis.EQ));
//		boolean exists = this.agentService.exists(formMap);
		boolean exists = this.webAgentService.exists(tempAgentId);
		if (!exists) {
			this.saveActionError("用户不存在");
			jsonObject.element(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.element(ErrorMsg.KEY_MESSAGE, "用户不存在");
//			return "!/agent/SafeSet/queryMessage.do";
			return this.writeJson(jsonObject);
		}
		exists = this.webAgentService.existsByPhone(newMobile);
		if (exists) {
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"该手机号码已被绑定，请重新输入");
			return this.writeJson(jsonObject);
		}
		// 更新数据库
		RsAgent agent = new RsAgent();
		agent.setMobile(newMobile);
		agent.setAgentId(this.getSessionUser().getAgentId());
//		formMap.put("rsAgent", agent);
		try
		{
//		this.agentService.update(formMap);
	    this.webAgentService.updateAgent(agent,tempAgentId);
		// 记录操作日志
		
		this.logService.addAgentAuditLog("", "用户为："+this.getSessionUser().getUserName()+"重置了"+this.getSessionUser().getAgentName()+"代理商的手机号");
		// 更新session
		this.getSessionUser().setAgentMobile(newMobile);
		this.saveActionMessage("更改手机号码成功!");
		jsonObject.element(ErrorMsg.KEY_CODE,ErrorMsg.CALL_OK);
        jsonObject.element(ErrorMsg.KEY_MESSAGE, "调用成功");
		}catch (BusinessException e) {
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
		}
		return this.writeJson(jsonObject); //返回结果
//		return "!/agent/SafeSet/queryMessage.do";
	}
	/**
	 * 重置登录密码
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String resetLoginPwd() {
		JSONObject jsonObject = new JSONObject();
		String tempUserId = this.getSessionUser().getUserId();
		// 检查是否存在用户
//		formMap.put(RsUser.COL_USER_ID, this.getSessionUser().getUserId());
//		SqlUtis.prepareSql(formMap, SqlUtis.getSQLRequired(formMap, "a."
//				+ RsUser.COL_USER_ID, Types.VARCHAR, SqlUtis.EQ));
//		boolean exists = this.userService.exists(formMap);
		boolean exists = this.userAgentService.exists(tempUserId);
		if (!exists) {
			jsonObject.element(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
            jsonObject.element(ErrorMsg.KEY_MESSAGE, "用户不存在");
            return this.writeJson(jsonObject);
		}
//		RsUser user = this.userService.one(formMap);
		RsUser user = this.userAgentService.getRsUserByUserId(tempUserId);
		
//		//检查是否启用
//		if(user.getStatus()!=null && user.getStatus().equals("0")){
//			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
//			jsonObject.put(ErrorMsg.KEY_MESSAGE,"该账户已经停用");
//			return this.writeJson(jsonObject);
//		}
		
		if (!oldLoginPwd.equals(user.getPassword())) {
			jsonObject.element(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
            jsonObject.element(ErrorMsg.KEY_MESSAGE, "原密码不正确");
            return this.writeJson(jsonObject);
		}
		user.setPassword(newLoginPwd);
//		formMap.put("rsUser", user);
//		this.userService.update(formMap);
		try{
		this.userAgentService.updateUserLogPwd(user,tempUserId);
		// 记录操作日志
		this.logService.addAgentAuditLog("", "用户编码为："+this.getSessionUser().getUserName()+"重置了"+this.getSessionUser().getAgentName()+"代理商的登录密码");
		jsonObject.element(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
        jsonObject.element(ErrorMsg.KEY_MESSAGE, "重置登录密码成功");
		this.saveActionMessage("重置登录密码成功!");
		}catch (BusinessException e) {
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
		}
//		return "!/agent/SafeSet/queryMessage.do";
		return this.writeJson(jsonObject);
	}
	/**
	 * 重置支付密码
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String resetPayPwd() {
		JSONObject jsonObject = new JSONObject();
		String agentId = this.getSessionUser().getAgentId();
//		formMap.put(TsAccount.COL_OWNER_ID, agentId);
//		formMap.put(TsAccount.COL_OWNER_TYPE_ID, "1"); //设置支付类型
//		SqlUtis.prepareSql(formMap, SqlUtis.getSQL(formMap, "a."
//				+ TsAccount.COL_OWNER_TYPE_ID, Types.VARCHAR, SqlUtis.EQ),
//				SqlUtis.getSQL(formMap, "a." + TsAccount.COL_OWNER_ID, Types.VARCHAR, SqlUtis.EQ));
//		TsAccount account = this.accountService.one(formMap);
		TsAccount account = this.userAgentService.getTsAccount(agentId, "2");
		if(account == null){
			jsonObject.element(ErrorMsg.KEY_CODE,ErrorMsg.CALL_FAIL);
			jsonObject.element(ErrorMsg.KEY_MESSAGE, "该代理商暂无账户信息！");
//			this.saveActionError("该代理商暂无账户信息！");
//			return "/agent/resetPayPwd.jsp";
			return this.writeJson(jsonObject);
		}else{
			if (!oldPayPwd.equals(account.getPassword())) {
				jsonObject.element(ErrorMsg.KEY_CODE,ErrorMsg.CALL_FAIL);
				jsonObject.element(ErrorMsg.KEY_MESSAGE, "旧支付密码输入有误！");
				this.saveActionError("旧支付密码输入有误！");
//				return "/agent/resetPayPwd.jsp";
		        return this.writeJson(jsonObject);
			}
			account.setPassword(newPayPwd);
//			formMap.put("tsAccount", account);
//			this.accountService.update(formMap);
			try{
			this.userAgentService.updateTsAccountPayPwd(account,agentId);
			// 记录操作日志
			this.logService.addAgentAuditLog("", "用户编码为："+this.getSessionUser().getUserName()+"重置了"+this.getSessionUser().getAgentName()+"代理商的支付密码");
			this.saveActionMessage("重置支付密码成功!");
//			return "!/agent/SafeSet/queryMessage.do";
			jsonObject.element(ErrorMsg.KEY_CODE,ErrorMsg.CALL_OK);
			jsonObject.element(ErrorMsg.KEY_MESSAGE, "重置支付密码成功!");
			}catch (BusinessException e) {
				jsonObject = JSONObject.fromObject(e.getErrorMsg());
			} catch (Exception e) {
				jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
			}
			return this.writeJson(jsonObject);
		}
	}
	
	/**
	 * 个人备付金账户
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public String queryAccount(){
	
		
		JSONObject jsonObject=new JSONObject();
		
		try{
			
			String agentId = this.getSessionUser().getAgentId();
			formMap.put(TsAccount.COL_OWNER_ID, agentId);
			formMap.put(TsAccount.COL_OWNER_TYPE_ID, "2");
			SqlUtis.prepareSql(formMap, SqlUtis.getSQL(formMap, "a."
					+ TsAccount.COL_OWNER_ID, Types.VARCHAR, SqlUtis.EQ),
			SqlUtis.getSQL(formMap,"a."+TsAccount.COL_OWNER_TYPE_ID,Types.VARCHAR,SqlUtis.EQ));
			TsAccount account = this.accountService.one(formMap);
			
			if(account != null && !account.getStatusId().equals("05")){
				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);

				jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用成功");
			}else{
				
				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);

				jsonObject.put(ErrorMsg.KEY_MESSAGE,"-1");
				
			}
				
		}catch(Exception e){
			
			
			e.printStackTrace();
			
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);

			jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用失败");
		}
		
		
		return this.writeJson(jsonObject);
	}

	/**
	 * 绑定备付金账户
	 * @return
	 */
	public String addUserAccount(){
		
		JSONObject jsonObject=new JSONObject();
		
		try{
			tsAccount.setOwnerId(this.getSessionUser().getAgentId());
			tsAccount.setAccountTypeId("1");
			tsAccount.setOwnerTypeId("2");
			tsAccount.setBalance(tsAccount.getBalance()==null?Double.parseDouble("0.00"):tsAccount.getBalance());
			tsAccount.setPassword(tsAccount.getPassword());
			
			String agentId = this.getSessionUser().getAgentId();
			formMap.put(TsAccount.COL_OWNER_ID, agentId);
			formMap.put(TsAccount.COL_OWNER_TYPE_ID, "2");
			SqlUtis.prepareSql(formMap, SqlUtis.getSQL(formMap, "a."
					+ TsAccount.COL_OWNER_ID, Types.VARCHAR, SqlUtis.EQ),
			SqlUtis.getSQL(formMap,"a."+TsAccount.COL_OWNER_TYPE_ID,Types.VARCHAR,SqlUtis.EQ));
			TsAccount account = this.accountService.one(formMap);
			
			if(account!=null && account.getStatusId().equals("05")){//激活
				jsonObject=accountPayService.activate("", tsAccount.getOwnerId(),tsAccount.getOwnerTypeId(),tsAccount.getPassword());
			}else{
				Map map = new HashMap();
				//		map.put("tsAccount", tsAccount);
				
				//		tsAccountService.insert(map);
				//shopsService.insertAccount(tsAccount);
				
				accountPayService.create(tsAccount.getOwnerId(), tsAccount.getOwnerTypeId(), tsAccount.getPassword(), tsAccount.getSignType(), tsAccount.getBalance()+"","");
				
				//this.saveActionMessage("绑定备付金账户成功！");
				//this.logService.addAdminAuditLog("", "绑定备付金账户成功,商家代码:"+tsAccount.getOwnerId());//记录操作日志
				
			}
			
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
	
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"新增支付密码成功");
		
		
		}catch(Exception e){
			
			
			e.printStackTrace();
			
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);

			jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用失败");
		}
		
		
		return this.writeJson(jsonObject);
		
	}
	
	/**
	 * 显示个人旧手机号
	 * 
	 * @return
	 */
	public String showPersonMobile() {
		
		JSONObject jsonObject=new JSONObject();
		
		try {
			oldMobile = this.getSessionUser().getMobile();
			
			jsonObject.put("oldMobile", oldMobile);
			
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用成功");
			
		} catch (Exception e) {
			e.printStackTrace();
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用失败");
		}
		
		return this.writeJson(jsonObject);
	}

	/**
	 * 重置个人手机号
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String resetPersonMobile() {
		// 检查是否存在用户
		
		JSONObject jsonObject=new JSONObject();
		
		try {
			formMap.put(RsUser.COL_USER_ID, this.getSessionUser().getUserId());
			SqlUtis.prepareSql(formMap, SqlUtis.getSQLRequired(formMap, "a."
					+ RsUser.COL_USER_ID, Types.VARCHAR, SqlUtis.EQ));
			boolean exists = this.userService.exists(formMap);
			if (!exists) {
				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
				jsonObject.put(ErrorMsg.KEY_MESSAGE,"用户不存在");
				return this.writeJson(jsonObject);
			}
			
			formMap.put(RsUser.COL_MOBILE, newMobile);
			SqlUtis.prepareSql(formMap, SqlUtis.getSQLRequired(formMap, "a."
					+ RsUser.COL_MOBILE, Types.VARCHAR, SqlUtis.EQ));
			exists = this.userService.exists(formMap);
			if (exists) {
				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
				jsonObject.put(ErrorMsg.KEY_MESSAGE,"该手机号码已被绑定，请重新输入");
				return this.writeJson(jsonObject);
			}
			
			// 更新数据库
			RsUser user=new RsUser();
			user.setMobile(newMobile);
			user.setUserId(this.getSessionUser().getUserId());
			formMap.put("rsUser", user);
			this.userService.update(user);
			// 记录操作日志
			this.logService.addAgentAuditLog("", "重置"+user.getUserId()+"手机号为:"+user.getMobile());
			// 更新session
			this.getSessionUser().setMobile(newMobile);
			
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"更改个人手机号码成功!");
			
		} catch (Exception e) {
			e.printStackTrace();
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用失败");
		}
		
		return this.writeJson(jsonObject);
		
	}

}
